import classNames from 'classnames'
import React, { useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'

type Props = Omit<React.DetailedHTMLProps<React.TextareaHTMLAttributes<HTMLTextAreaElement>, HTMLTextAreaElement>, 'value' | 'maxLength' | 'onChange'> & {
  className?: string
  value?: string
  onChange?: (e: React.ChangeEvent<HTMLTextAreaElement>) => void
  maxLength?: number
}
export default function Textarea({ className, maxLength = 100, value, onChange, ...rest }: Props) {
  const [content, setContent] = useState(value || '')
  const textRef = useRef<HTMLTextAreaElement>(null)
  useEffect(() => {
    textRef.current!.focus()
    textRef.current!.setSelectionRange(-1, -1)
  }, [])
  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setContent(e.target.value)
    onChange && onChange(e)
  }
  return (
    <div className={styles.root}>
      <textarea ref={textRef} {...rest} className={classNames('textarea', className)} maxLength={maxLength} value={content} onChange={handleChange} />

      {/* 当前字数/最大允许字数 */}
      <div className="count">
        {content.length}/{maxLength}
      </div>
    </div>
  )
}
